import { useState, useEffect, useCallback } from 'react';

const AIChatBox = () => {
    const [messages, setMessages] = useState([]);
    const [input, setInput] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [isListening, setIsListening] = useState(false);
    let recognition = null;

    const sendMessage = async (e) => {
        e.preventDefault();
        if (!input.trim()) return;

        setIsLoading(true);
        const userMessage = { role: 'user', content: input };
        setMessages(prev => [...prev, userMessage]);

        try {
            const response = await fetch('https://api.deepseek.com/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${process.env.REACT_APP_DEEPSEEK_API_KEY}`
                },
                body: JSON.stringify({
                    model: 'deepseek-chat',
                    messages: [...messages, userMessage],
                    stream: false
                })
            });

            const data = await response.json();
            setMessages(prev => [...prev, data.choices[0].message]);
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setIsLoading(false);
            setInput('');
        }
    };

    // 初始化语音识别
    const initSpeechRecognition = useCallback(() => {
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        if (SpeechRecognition) {
            recognition = new SpeechRecognition();
            recognition.lang = 'zh-CN';
            recognition.continuous = false;
            recognition.interimResults = false;

            recognition.onresult = (event) => {
                const transcript = event.results[0][0].transcript;
                setInput(transcript);
                setIsListening(false);
            };

            recognition.onerror = (event) => {
                console.error('语音识别错误:', event.error);
                setIsListening(false);
            };

            recognition.onend = () => {
                setIsListening(false);
            };
        }
    }, []);

    // 切换语音输入
    const toggleVoiceInput = () => {
        if (!recognition) {
            initSpeechRecognition();
        }

        if (!recognition) {
            alert('您的浏览器不支持语音识别功能');
            return;
        }

        if (isListening) {
            recognition.stop();
        } else {
            setInput('');
            recognition.start();
            setIsListening(true);
        }
    };

    // 清理函数
    useEffect(() => {
        return () => {
            if (recognition) {
                recognition.stop();
            }
        };
    }, []);

    return (
        <div className="chat-container">
            <div className="messages">
                {messages.map((message, index) => (
                    <div key={index} className={`message ${message.role}`}>
                        {message.content}
                    </div>
                ))}
            </div>

            <form onSubmit={sendMessage}>
                <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    placeholder="输入消息..."
                    disabled={isLoading || isListening}
                />
                <button
                    type="button"
                    className={`voice-btn ${isListening ? 'listening' : ''}`}
                    onClick={toggleVoiceInput}
                    disabled={isLoading}
                >
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="currentColor" d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3zm5.91-3c-.49 0-.9.36-.98.85C16.52 14.2 14.47 16 12 16s-4.52-1.8-4.93-4.15c-.08-.49-.49-.85-.98-.85-.61 0-1.09.54-1 1.14.49 3 2.89 5.35 5.91 5.78V20c0 .55.45 1 1 1s1-.45 1-1v-2.08c3.02-.43 5.42-2.78 5.91-5.78.1-.6-.39-1.14-1-1.14z"/>
                    </svg>
                </button>
                <button type="submit" disabled={isLoading || isListening || !input.trim()}>
                    发送
                </button>
            </form>

            {isLoading && (
                <div className="loading-indicator">
                    <div className="typing-indicator">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                    <p>AI正在思考中...</p>
                </div>
            )}
        </div>
    );
};

export default AIChatBox; 